//
//  WLPhotoCloudController.m
//  WanLian
//
//  Created by xz on 2018/9/7.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLPhotoCloudController.h"
#import "WLCloudPhotoModel.h"
#import "WLPhotoSubModel.h"
#import "WLCloudPhotoCell.h"
#import "WLPhotoLookVController.h"
#import "UIScrollView+EmptyDataSet.h"
#import "WLSuportFileFormat.h"
#import "WLUseManager.h"

static NSString *photoCell = @"photoCell";
@interface WLPhotoCloudController ()<UICollectionViewDelegate,UICollectionViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) NSMutableArray *arrPhotos;
@property (nonatomic, assign) NSInteger pagePhoto;
@property (nonatomic, assign) BOOL needRefresh;
//@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation WLPhotoCloudController
- (void)receiveUploadSuccessNofication:(NSNotification *)notifi {
    self.pagePhoto = 1;
    [self reqCloudPhoto];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kUploadSuccessNofication object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KRRefreshPhotoCloudNotification object:nil];
}
- (void)RefreshPage {
    self.needRefresh = YES;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.needRefresh == YES) {
        self.needRefresh = NO;
        self.pagePhoto = 1;
        [self reqCloudPhoto];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveUploadSuccessNofication:) name:kUploadSuccessNofication object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RefreshPage) name:KRRefreshPhotoCloudNotification object:nil];
    WLWkSelf
    _arrPhotos = [[NSMutableArray alloc] init];
    _pagePhoto = 1;
    
    UICollectionViewFlowLayout *flowLatyout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = (WIDTH_SCREEN_WL-WLScaleX(32)-WLScaleX(20))/5.0;
    if (WIDTH_SCREEN_WL<375) {
        width = (WIDTH_SCREEN_WL-WLScaleX(32)-WLScaleX(20))/4.0;
    }
    flowLatyout.itemSize = CGSizeMake(width, width);
    flowLatyout.sectionInset = UIEdgeInsetsMake(WLScaleX(5), WLScaleX(16), WLScaleX(5), WLScaleX(16));
    flowLatyout.minimumInteritemSpacing = WLScaleX(5);
    flowLatyout.minimumLineSpacing = WLScaleX(5);
    flowLatyout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    flowLatyout.headerReferenceSize = CGSizeMake(WIDTH_SCREEN_WL, WLScaleX(44));  //设置headerView大小
    
    _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLatyout];
    _collectionView.backgroundColor = wlBackColor;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    [_collectionView registerClass:[WLCloudPhotoCell class] forCellWithReuseIdentifier:photoCell];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    self.collectionView.emptyDataSetSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    
    _collectionView.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.pagePhoto = 1;
        weakSelf.collectionView.mj_footer = nil;
        [weakSelf reqCloudPhoto];
    }];
    
    [self reqCloudPhoto];
    /*
    _tbPhoto = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbPhoto.delegate = self;
    _tbPhoto.dataSource = self;
    _tbPhoto.rowHeight = WLScaleX(64);
    _tbPhoto.tableFooterView = [UIView new];
    if (@available(iOS 11.0, *)) {
        _tbPhoto.estimatedSectionHeaderHeight = 0;
    }
    [self.view addSubview:_tbPhoto];
    [_tbPhoto mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    _tbPhoto.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.tbPhoto.mj_footer = nil;
//        [weakSelf.arrPhotos removeAllObjects];
        weakSelf.pagePhoto = 1;
        [weakSelf reqCloudPhoto];
    }];
    
    [weakSelf reqCloudPhoto];
    */
}

- (void)addPhotoFooterRefresh
{
    WLWkSelf
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reqCloudPhoto];
    }];
}

- (void)reqCloudPhoto
{
    WLWkSelf
//    NSDictionary *conditions = @{@"fileType":@1};
//    NSDictionary *pages = @{@"page":@(_pagePhoto),@"num":@10};
//    NSDictionary *params = @{@"conditions":conditions,@"page":pages};
    NSString *url = nil;
    if ([WLCommonTool isConnectedTianYiLian]) {
        url = [NSString stringWithFormat:@"%@/cgi-bin/luci/file/upload/list?fileType=1", HTTP_HOST_ROUTER];
    } else {//http://router.skywindlink.com/router/storage/item/type/0/c12478fa924e3371283f2b9a0bfc921a
        url = [NSString stringWithFormat:@"%@/storage/item/type/1/%@", HTTP_HOST_WEB,[[WLUseManager shareUser] getUserCurrentRouter]];
    }
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:url withParamsDic:nil success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.collectionView.mj_header endRefreshing];
        NSInteger productCount = [successDict[@"object"] count];
        if (strongSelf.pagePhoto==1)
        {
            [strongSelf.arrPhotos removeAllObjects];
//            if (productCount>10)
//            {
//                [strongSelf addPhotoFooterRefresh];
//            }
        }
//        NSArray *arrItems = successDict[@"object"];
//        if (arrItems.count>0) {
//            [strongSelf.arrPhotos addObjectsFromArray:arrItems];
//        }
        
        NSArray *arrPros = [WLCloudPhotoModel mj_objectArrayWithKeyValuesArray:successDict[@"object"]];
        if (arrPros.count>0) {
            [strongSelf.arrPhotos addObjectsFromArray:arrPros];
            if (strongSelf.arrPhotos.count >= productCount) {
                [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.collectionView.mj_footer endRefreshing];
            }
            //            [strongSelf.tbRouter reloadData];
        }
        else
        {
            [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        [strongSelf.collectionView reloadData];
//        strongSelf.pagePhoto += 1;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf celarData];
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf celarData];
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    } inView:self.view];
}
- (void)celarData {
    [self.arrPhotos removeAllObjects];
    [self.collectionView reloadData];
}
#pragma mark collectionView代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _arrPhotos.count;
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
//{
//
//    return CGSizeMake([[UIScreen mainScreen] bounds].size.width, 40);
//}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
    for (UIView *subView in headerView.subviews) {
        [subView removeFromSuperview];
    }
    UILabel *labTime = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(20), 120, WLScaleX(20))];
    labTime.font = [WLCommonTool fontTypePingFangSCMedium:14];
    labTime.textColor = wlBlackColor;
    [headerView addSubview:labTime];
    labTime.text = [_arrPhotos[indexPath.section] time];
    return headerView;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *arrItems = [_arrPhotos[section] items];
    return arrItems.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WLCloudPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:photoCell forIndexPath:indexPath];
    
    WLCloudPhotoModel*photoModel = self.arrPhotos[indexPath.section];
    WLPhotoSubModel *fileModel = photoModel.items[indexPath.row];
    cell.ivImg.contentMode = UIViewContentModeScaleAspectFill;
    cell.ivImg.clipsToBounds = YES;
    if (![WLSuportFileFormat photoSupportFormat:fileModel.fileName]) {
        cell.ivImg.image = [UIImage imageNamed:@"CloudImageNotSupport"];
    } else {
        if (fileModel.url.length>0) {
            [cell.ivImg sd_setShowActivityIndicatorView:YES];
            [cell.ivImg sd_setIndicatorStyle:UIActivityIndicatorViewStyleGray];
            
            NSURL *url = [NSURL URLWithString:fileModel.url];
            [cell.ivImg sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"CloudImadgeLoading"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (error) {
                    cell.ivImg.image = [UIImage imageNamed:@"CloudImadgeLoadFail"];
                }
            }];
        }
        else
        {
            cell.ivImg.image = [UIImage imageNamed:@"CloudImageNotSupport"];
        }
    }
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    WLCloudPhotoCell *cell = (WLCloudPhotoCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    WLCloudPhotoModel*photoModel = self.arrPhotos[indexPath.section];
    WLPhotoSubModel *fileModel = photoModel.items[indexPath.row];
    
    if (cell.ivImg != nil) {
        WLPhotoLookVController *photoController = [[WLPhotoLookVController alloc] init];
        photoController.photoModel = fileModel;
        [self.navigationController pushViewController:photoController animated:YES];
    }
}

#pragma mark - DZNEmpty
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"no_photo"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"还没有上传照片哦~";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[WLCommonTool fontTypePingFangSCRegular:17],
                                 NSForegroundColorAttributeName:wlDarkGrayColor
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
//{
//    
//}

//- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view
//{
//
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
